package com.alogic.xscript.plugins;

import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.IOTools;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.Console;
import java.io.InputStreamReader;

/**
 * 标准输入
 *
 * @since 1.6.14.3 [20210322 duanyy] <br>
 */
public class Stdin extends AbstractLogiclet {
    protected String id;
    protected String $msg;

    public Stdin(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);

        id = PropertiesConstants.getString(p,"id",id,true);
        $msg = PropertiesConstants.getRaw(p,"msg",$msg);
    }

    @Override
    protected void onExecute(XsObject root, XsObject current, LogicletContext ctx, ExecuteWatcher watcher) {
        if (StringUtils.isNotEmpty(id)){
            Console console = System.console();
            if (console == null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
                try {
                    String msg = PropertiesConstants.transform(ctx,$msg,"");
                    if (StringUtils.isNotEmpty(msg)){
                        System.out.print(msg);
                    }
                    String line = reader.readLine();
                    if (StringUtils.isNotEmpty(line)) {
                        ctx.SetValue(id, line);
                    }
                } catch (Exception ex) {
                    log("Cannot read line from system.in.");
                } finally {
                    IOTools.close(reader);
                }
            }else{
                String line = console.readLine(PropertiesConstants.transform(ctx,$msg,""));
                if (StringUtils.isNotEmpty(line)) {
                    ctx.SetValue(id, line);
                }
            }
        }
    }
}

